import random
from io import BytesIO

from PIL import Image, ImageDraw, ImageFont, ImageFilter


class Captcha:
    @staticmethod
    def add_noise(captcha_image):
        # 假设captcha_image是一个已经生成的验证码图片对象
        # 转换为灰度图
        captcha_image = captcha_image.convert('L')
        # 创建一个新的图层来添加噪点
        noise_layer = Image.eval(captcha_image, lambda x: x + 25 if random.randint(0, 2) else x)
        # 将原图和噪点图层叠加
        captcha_image = Image.composite(captcha_image, noise_layer, noise_layer)

        return captcha_image

    @staticmethod
    def create_captcha(code='', format='JPEG', width=120, height=40):
        """ 生成验证码图片 """
        image = Image.new('RGB', (width, height), color=(255, 255, 255))
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype('static/fonts/Arial.ttf', 24)
        # 绘制字符
        draw.text((25, 5), code, font=font, fill=(0, 0, 0))

        # 应用噪点
        image = Captcha.add_noise(image)
        # 随机应用模糊效果
        image = image.filter(ImageFilter.GaussianBlur(random.randint(1, 2)))

        # 将验证码保存到内存中
        buffer = BytesIO()
        image.save(buffer, format='JPEG')

        return buffer.getvalue()


__all__ = ['Captcha']
